<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" custom-class="mydialog" width="50%"
    title="添加意向代理业务" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="100px" size="small">
      <el-row gutter="40">
        <el-col :span="20">
          <el-form-item label="代理产品" prop="productName">
            <el-autocomplete v-model="openForm.productName" style="width: 100%" placeholder="请输入代理产品"
              :fetch-suggestions="querySearchAgent" :loading="false" @select="handleSelecAgent">
              <template #default="{ item }">
                <div class="distributeName">
                  {{getProductName(item)}}
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>

        <el-col :span="20">
          <el-form-item label="代理地区" prop="area">
            <el-cascader ref="cascader" v-model="openForm.area" :popper-append-to-body="false" style="width: 100%;"
              :options="citys" placeholder="请选择代理地区"
              :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }" collapse-tags
              clearable @change="handlArea" />
          </el-form-item>
        </el-col>

        <el-col :span="20" prop="agentType">
          <el-form-item label="代理属性" prop="agentIntentionAttribute">
            <el-checkbox-group v-model="openForm.agentIntentionAttribute" @change="handlGroup">
              <el-checkbox v-for="(item,index) in agentAttribute" :key="index" :label="item.value">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>

        <template v-if="openForm.agentIntentionAttribute.indexOf('2') !== -1">
          <el-col :span="20">
            <el-form-item label="终端名称" prop="terminalName"
              :required="openForm.agentIntentionAttribute.indexOf('2') !== -1">
              <div class="box">
                <span v-for="(item,index) in openForm.terminalList" :key="item.id">
                  <span> {{ item.terminalName }}</span>
                  <span class="iconfont icon-shanchu1" style="cursor:pointer;color:red" @click="handlDele(index)" />
                  <span v-if="index !== openForm.terminalList.length - 1"> 、</span>
                </span>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label-width="0px">
              <el-button type="text" @click="handAdd">选择终端</el-button>
            </el-form-item>
          </el-col>
        </template>

        <el-col :span="20">
          <el-form-item label="其他描述" prop="address">
            <el-input v-model="openForm.desc" type="textarea" :rows="2" placeholder="请输入内容" />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">保存</el-button>
      </div>
    </template>
    <terminal ref="terminalRef" @succsess="succsess" />
  </el-dialog>

</template>

<script>
import {defineAsyncComponent, getCurrentInstance, inject, reactive, toRefs,} from "vue";
import area from "@/utils/area";
import {crmStore} from "@CRM/store";

export default {
  name: "AddAgent",
  components: {
    terminal: defineAsyncComponent(() => import("./terminal.vue")),
  },
  setup(props, context) {
    const api = inject("api");
    const currentInstance = getCurrentInstance();
    const data = reactive({
      openBoole: false,
      citys: area,
      cascader: null,
      openForm: {
        region: [],
        productName: "",
        productId: 0,
        area: [],
        agentIntentionAttribute: [],
        terminalName: "",
        terminalIdList: [],
        productLineName: "",
        terminalList: [],
        desc: "",
      },
      rules: {
        productName: [
          { required: true, message: "请选择代理产品", trigger: "change" },
        ],
        area: [
          { required: true, message: "请选择代理地区", trigger: "change" },
        ],
        agentIntentionAttribute: [
          { required: true, message: "请选择代理属性", trigger: "change" },
        ],
        terminalList: [
          { message: "请选择代终端", type: "array", trigger: "change" },
        ],
      },
      agentAttribute:
        crmStore.getters["dictionary/getDictionary"]["agentAttribute"],
      openRef: null,
      terminalRef: null,
    });

    const handlArea = (val) => {
      data.openForm.area = val;
      data.openForm.region = currentInstance.proxy.getServeAreaData(
        val,
        data.cascader.getCheckedNodes()
      );
      console.log(data.openForm.region, "--------");
    };

    const close = () => {
      data.openBoole = false;
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (val) => {
      data.openForm = {
        region: [],
        productName: "",
        productId: 0,
        area: [],
        agentIntentionAttribute: [],
        terminalName: "",
        terminalIdList: [],
        productLineName: "",
        terminalList: [],
      };
      if (val) {
        data.openForm = val;
        console.log(val, "------------");
        if (data.openForm.terminalList.length > 0) {
          data.openForm.terminalList.forEach((item) => {
            data.openForm.terminalIdList.push(item.id);
          });
        }
      }
      data.openBoole = true;
    };

    const querySearchAgent = async (queryString, cb) => {
      const res = await api.channelAgent.POTENTIALAGENT_PRODUCT(queryString);
      let results = [];
      if (res.code === 0) {
        results = res.data.list || [];
      }
      cb(results);
    };

    const handleSelecAgent = (val) => {
      data.openForm.productName = currentInstance.proxy.getProductName(val)
      data.openForm.productLineName = val?.productLineDetail?.productLineName;
      data.openForm.productId = val.id;
    };

    const handAdd = () => {
      data.openRef.validateField("area", (val) => {
        if (!val) {
          const list = {
            terminalList: data.openForm.terminalList,
            area: data.openForm.area,
            region: currentInstance.proxy.getServeAreaData(
              data.openForm.area,
              data.cascader.getCheckedNodes()
            ),
          };
          data.terminalRef.open(list);
        }
      });
    };

    const handlDele = (index) => {
      data.openForm.terminalList.splice(index, 1);
      succsess(data.openForm.terminalList);
    };

    const succsess = (val) => {
      data.openForm.terminalList = val;
      data.openForm.terminalList.forEach((item) => {
        data.openForm.terminalIdList.push(item.terminalId);
      });
      if (
        data.openForm.terminalList.length > 0 &&
        data.openForm.terminalList.length > 1
      ) {
        data.openForm.terminalName = `${data.openForm.terminalList[0].terminalName}等${data.openForm.terminalList.length}终端`;
      } else {
        data.openForm.terminalName = data.openForm.terminalList[0].terminalName;
      }
    };

    const handlGroup = (val) => {
      if (val.indexOf("2") === -1) {
        data.openForm.terminalList = [];
        data.openForm.terminalIdList = [];
        data.openForm.terminalName = "";
      }
    };

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          context.emit("succsess", { ...data.openForm });
          close();
        }
      });
    };

    return {
      ...toRefs(data),
      handlArea,
      close,
      open,
      querySearchAgent,
      handleSelecAgent,
      handlSubmit,
      handAdd,
      succsess,
      handlDele,
      handlGroup,
    };
  },
};
</script>

<style scoped>
.box {
  width: 100%;
  box-sizing: border-box;
  min-height: 44px;
  padding: 5px 15px;
  border: 1px solid #c0c4cc;
  border-radius: 4px;
}
</style>
